/*Copyright 2014 Rajesh Putta http://www.codesnippets4all.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* 
*/

package com.codesnippets4all.jthunder.extension.plugins.input;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import com.codesnippets4all.jthunder.core.IPlugin;
import com.codesnippets4all.jthunder.core.exceptions.AutomationException;
import com.codesnippets4all.jthunder.core.execution.IStatus;
import com.codesnippets4all.jthunder.core.execution.Status;
import com.codesnippets4all.jthunder.core.execution.StatusType;
import com.codesnippets4all.jthunder.core.execution.status.AutomationStatusManager;
import com.codesnippets4all.jthunder.core.state.IContext;

/*
 * @author Rajesh Putta
 */
public class BinaryFileInputPlugin implements IPlugin  {

	public IStatus process(Map<String, String> configuration, IContext context,
			AutomationStatusManager statusManager) {
		
		String filepath = configuration.get("filepath");
		
		if(filepath==null || filepath.trim().equals(""))
		{
			throw new AutomationException("BinaryFileInputPlugin component requires 'filepath' to be configured in task configuration...");
		}
		
		//read text file content block by block for effective reading
		byte[] buffer=new byte[2048];
		
		int offset=-1;
		
		BufferedInputStream iStream=null;

		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		
		try{	
			iStream=new BufferedInputStream(new FileInputStream(filepath));
			
			while((offset=iStream.read(buffer))!=-1)
			{
				baos.write(buffer, 0, offset);
			}
		}
		catch (Exception e) {
			throw new AutomationException(e);
		}
		finally{
			if(iStream!=null)
			{
				try {
					iStream.close();
				} catch (IOException e) {
				}
			}
			
			buffer=null;
		}
		
		
		IStatus status=new Status(StatusType.SUCCESS, baos.toByteArray());
		
		return status;
	}

}
